﻿namespace PowerSong.UserInterface
    {
    using System;
    using System.Collections.Generic;
    using System.Data;
    using PowerSong.SongDatabase;

    public class SongUsageReport : Report
        {

        public DataTable Report { get; private set; }

        private DateTime startDate;

        private DateTime endDate;

        public SongUsageReport(DateTime startDate, DateTime endDate)
            {
            this.startDate = startDate;
            this.endDate = endDate;
            }

        public override void Execute()
            {

            // Create the data table we will populate
            this.Report = new DataTable("SongUsageReport");
            this.Report.Columns.Add("Title");
            this.Report.Columns.Add("License");
            this.Report.Columns.Add("TimesPlayed", typeof(int));

            // Process each record
            var timesPlayed = new Dictionary<Guid, int>();
            foreach (var entry in State.Database.ActivityLog.Get(startDate, endDate))
                {
                if (entry.Type == ActivityItemType.Song && entry.ActionPerformed == ActivityAction.Shown)
                    {
                    if (timesPlayed.ContainsKey(entry.ItemID))
                        {
                        timesPlayed[entry.ItemID] += 1;
                        }
                    else
                        {
                        timesPlayed.Add(entry.ItemID, 1);
                        }
                    }
                }

            // Now create the actual report
            foreach (var entry in timesPlayed)
                {

                // Add basic details
                var row = this.Report.NewRow();
                row["TimesPlayed"] = entry.Value;

                // Get the title and license
                var song = State.Database.Songs.Get(entry.Key);
                row["Title"] = song == null ? "Unknown Item" : song.Title;
                row["License"] = song == null || song.License == null ? "Unknown License" : song.License.Name;

                // Add the row to the table
                this.Report.Rows.Add(row);

                }

            }

        }

    }